package com.ruoyi.utils;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author: MrPing
 * @createTime: 2022/3/21 11:26
 * @description:
 */
public class AliCosUtils {

    // Endpoint
    protected static final String ENDPOINT = "https://oss-cn-shenzhen.aliyuncs.com";
    // AccessKey 在AccessKey管理获取 -->登录后-->头像-->AccessKey管理
    protected static final String ACCESSKEYID = "LTAI5tNnUtC8jempHZLvExTx";
    // accessKeySecret 在AccessKey管理获取 -->登录后-->头像-->AccessKey管理
    protected static final String ACCESSKEYSECRET = "HjrOHsuI1NIVGfpSEn9tOIezBCaTop";
    // Bucket
    protected static final String BUCKETNAME = "yuyitang";
    //访问域名(阿里云)
    private static String COS_BASE_URL = "https://yuyitang.oss-cn-shenzhen.aliyuncs.com";

    public static String uploadFile(MultipartFile file, String path){

        String result = null;
        // 私有云要关闭CNAME
        ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
        conf.setSupportCname(false);
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESSKEYID, ACCESSKEYSECRET, conf);
        try {
            InputStream inputStream = file.getInputStream();

            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKETNAME, path, inputStream);

            ossClient.putObject(putObjectRequest);

            result = COS_BASE_URL + "/" + path;
            System.out.println("图片地址：" + result);

        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }finally {
            // 关闭客户端
            ossClient.shutdown();
        }
        return result;

    }

}
